package com.ehualu.core.util.sms.service;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ehualu.core.property.PropertyConfig;
import com.ehualu.core.util.RandomCard;
import com.ehualu.core.util.sms.pojo.Sms;
import com.ehualu.core.util.sms.pojo.SmsResponse;
import com.ehualu.core.util.sms.pojo.SmsResponseStatus;

/**
 * 一信通短信接口
 * @author Administrator
 *
 */
public class UMSSmsService{

private static final Logger logger = LoggerFactory.getLogger(UMSSmsService.class);
	
	/**
	 * 短信发送(一信通)
	 * @return
	 */
	public String sendSms(Sms sms) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 您的验证码是236598，请于3分钟内正确输入，收到信息的请在QQ上回一声【易华录】
			StringBuilder sb = new StringBuilder();
			sb.append(PropertyConfig.getProperty("UMS_SMS_URL"))
					.append("?SpCode=")
					.append(PropertyConfig.getProperty("UMS_SP_CODE"))
					.append("&LoginName=")
					.append(PropertyConfig.getProperty("UMS_LOGIN_NAME"))
					.append("&Password=")
					.append(PropertyConfig.getProperty("UMS_SMS_PWD"))
					.append("&MessageContent=")
					.append(URLEncoder.encode(sms.getMessage(), "gbk"))
					.append("&UserNumber=").append(sms.getPhone())
					.append("&SerialNumber=").append(createNewOrderID())
					.append("&ScheduleTime=")
					.append("&f=1");
			logger.info("短信发送内容: " + sb.toString());
            HttpPost httpPost = new HttpPost(PropertyConfig.getProperty("UMS_SMS_URL"));
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("SpCode",PropertyConfig.getProperty("UMS_SP_CODE")));
            list.add(new BasicNameValuePair("LoginName",PropertyConfig.getProperty("UMS_LOGIN_NAME")));
            list.add(new BasicNameValuePair("Password", PropertyConfig.getProperty("UMS_SMS_PWD")));
            list.add(new BasicNameValuePair("MessageContent", URLEncoder.encode(sms.getMessage(), "gbk")));
            list.add(new BasicNameValuePair("UserNumber", sms.getPhone()));
            list.add(new BasicNameValuePair("SerialNumber", createNewOrderID()));
            list.add(new BasicNameValuePair("ScheduleTime", ""));
            list.add(new BasicNameValuePair("f", "1"));
            UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(list);
            httpPost.setEntity(requestEntity);
			logger.info("执行短信发送: ");
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpPost);
			// 获取响应实体
			HttpEntity entity = response.getEntity();
			logger.info("--------------------------------------");
			// 打印响应状态
			logger.info(response.getStatusLine().toString());
			String entityString = null;
			if (entity != null) {
				// 打印响应内容长度
				logger.info("响应内容长度: " + entity.getContentLength());
				entityString = EntityUtils.toString(entity, "gbk");
				// 打印响应内容
				logger.info("响应内容: " + entityString);
				
				logger.info("------------------------------------");
				String[] entityStr = entityString.split("&");
				Map<String,String> map = new HashMap<String,String>();
				for(int i=0;i<2;i++){
					String mapStr = entityStr[i];
					System.out.println("mapStr=============="+mapStr);
					if(mapStr != null){
						String[] keyValueStr = mapStr.split("=");
						map.put(keyValueStr[0], keyValueStr[1]);
					}
				}
				if(("0").equals(map.get("result"))){
					return JSON.toJSONString(new SmsResponse(SmsResponseStatus.SUCCESS.getStatus(),SmsResponseStatus.SUCCESS.getCode(),SmsResponseStatus.SUCCESS.getReason()));
				}else{
					return JSON.toJSONString(new SmsResponse(SmsResponseStatus.FAIL.getStatus(),map.get("result"),map.get("description")));
				}
			}else{
				return JSON.toJSONString(new SmsResponse(SmsResponseStatus.RESULT_IS_NULL.getStatus(),SmsResponseStatus.RESULT_IS_NULL.getCode(),SmsResponseStatus.RESULT_IS_NULL.getReason()));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.REQUEST_ERROR.getStatus(),SmsResponseStatus.REQUEST_ERROR.getCode(),SmsResponseStatus.REQUEST_ERROR.getReason()));
		} catch (ParseException e) {
			e.printStackTrace();
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.DATA_PARSE_EXCEPTION.getStatus(),SmsResponseStatus.DATA_PARSE_EXCEPTION.getCode(),SmsResponseStatus.DATA_PARSE_EXCEPTION.getReason()));
		} catch (IOException e) {
			e.printStackTrace();
			return JSON.toJSONString(new SmsResponse(SmsResponseStatus.SYSTEM_IS_EXCEPTION.getStatus(),SmsResponseStatus.SYSTEM_IS_EXCEPTION.getCode(),SmsResponseStatus.SYSTEM_IS_EXCEPTION.getReason()));
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
				return JSON.toJSONString(new SmsResponse(SmsResponseStatus.CLOSE_HTTPCLIENT_FAIL.getStatus(),SmsResponseStatus.CLOSE_HTTPCLIENT_FAIL.getCode(),SmsResponseStatus.CLOSE_HTTPCLIENT_FAIL.getReason()));
			}
		}
	}
	
	public String createNewOrderID(){
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	    StringBuilder tempOrderId = new StringBuilder(dateFormat.format(new Date()));
	    tempOrderId.append(RandomCard.getRandomNum(3, RandomCard.RandomFormat.NUM));
	    return tempOrderId.toString();
	  }
	
	public static void main(String[] args) {
		UMSSmsService us = new UMSSmsService();
		Sms sms = new Sms();
		sms.setMessage("您的验证码是{CDFA}请您于{5}分钟内输入");
		sms.setPhone("18660811312");
		us.sendSms(sms);
	}
}
